package cn.larry.common.utils.wx;

import com.alibaba.fastjson2.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import javax.validation.constraints.NotNull;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * This is created,
 * but not necessarily updated by me.
 * Therefore, AUTHOR is useless.
 * 2024/1/23 17:37
 * 【紧急通知应用】
 * 参考：https://developer.work.weixin.qq.com/document/path/91623
 * 医疗行业的企业，可通过语音电话提醒员工查看应用推送的重要消息，以便尽快处理紧急事件
 *
 * @Version 1.0
 */
@Slf4j
@Component
public class QywxCallTool {

    @Autowired
    public RestTemplate restTemplate;

//    @PostConstruct
//    public void mainsss() {
//        List<String> qywxIds = new ArrayList<>();
//        qywxIds.add("linliang");
//        call(qywxIds);
//    }

    /**
     * 发起语言电话
     *
     * @param qywxIds
     * @return
     */
    public boolean call(@NotNull List<String> qywxIds, String accessToken) {

        if(qywxIds==null || qywxIds.size()<1)
            return false;

        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("callee_userid", qywxIds);

        Map<String, String> uriVariables = new HashMap<>();
        uriVariables.put("token", accessToken);

        String postUrl = "https://qyapi.weixin.qq.com/cgi-bin/pstncc/call?access_token={token}";
        Map<String, Object> result = restTemplate.postForObject(postUrl, JSON.toJSONString(paramMap), Map.class, uriVariables);
        log.info("微信应答：{}", result);
        if (0 != (int) result.get("errcode")) {
            log.error("punchCorrection error：" + result);
            return false;
        }
        return true;
    }

    /**
     * 获取接听状态
     *
     * @param qywxId
     * @param callid
     */
    public void getstates(String qywxId, String callid, String accessToken) {

        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("callee_userid", qywxId);
        paramMap.put("callid", callid);

        Map<String, String> uriVariables = new HashMap<>();
        uriVariables.put("token", accessToken);

        String postUrl = "https://qyapi.weixin.qq.com/cgi-bin/pstncc/getstates?access_token={token}";
        Map<String, Object> result = restTemplate.postForObject(postUrl, JSON.toJSONString(paramMap), Map.class, uriVariables);
        log.info("微信应答：{}", result);
        if (0 != (int) result.get("errcode")) {
            log.error("punchCorrection error：" + result);
            return;
        }
        log.info(result.toString());
    }


}
